package com.dtsmoll.installapk;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.KeyEvent;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.dtsmoll.permissions.PermissionsUtils;

import java.io.File;

public class InstallApkActivity extends AppCompatActivity {

    public final static int INSTALL_APK = 10001;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        checkIsAndroidO();
    }

    private void checkIsAndroidO() {
        // 判断android版本是否需要申请权限
        if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            if (getPackageManager().canRequestPackageInstalls()) {
                installAPK();
            } else {
                // 请求安装权限
                PermissionsUtils.requestPermissions(this, new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES},
                        new PermissionsUtils.OnPermissionsCallback() {
                            @Override
                            public void onCallback(boolean status) {
                                if (status) { // 赋予权限
                                    installAPK();
                                } else {
                                    Uri packageURI = Uri.parse("package:" + getPackageName());
                                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                                    startActivityForResult(intent, INSTALL_APK);
                                }
                            }
                        });
            }
        } else {
            installAPK();
        }
    }

    // 安装apk
    private void installAPK() {
        File file = new File(InstallApkUtils.apkPath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 24) {
            Uri apkUri = FileProvider.getUriForFile(this, InstallApkUtils.authority, file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        startActivity(intent);
        InstallApkUtils.callback.onComplete(true);
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) { // 同意
            switch (requestCode) {
                case INSTALL_APK:
                    if (!TextUtils.isEmpty(InstallApkUtils.apkPath)) {
                        checkIsAndroidO();
                    }
                    break;
            }
        } else { // 取消
            InstallApkUtils.callback.onComplete(false);
            finish();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (InstallApkUtils.callback != null) {
                InstallApkUtils.callback.onComplete(false);
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
